from fastapi import FastAPI
from fastapi_pagination import add_pagination
from APP.config.conf import settings
from contextlib import asynccontextmanager
from APP.config.log_conf import log,setup_logging,set_customize_logfile
from APP.common.middleware.health_check import ensure_unique_route_names
from APP.database.mysql import create_table



def create_app():

    app = FastAPI(
        title=settings.FASTAPI_TITLE,
        version=settings.FASTAPI_VERSION,
        description=settings.FASTAPI_DESCRIPTION,
        docs_url=settings.FASTAPI_DOCS_URL,
        redoc_url=settings.FASTAPI_REDOCS_URL,
        openapi_url=settings.FASTAPI_OPENAPI_URL,
        lifespan= register_init,#生命周期管理函数
    )
    #初始化日志
    register_logger()

    #注册路由
    register_router(app)

    #分页
    register_page(app)


    return app

@asynccontextmanager
async def register_init(app: FastAPI):
    '''
    启动初始化
    '''
    log.info(
        """\n
/$$$$$$$$                   /$$      /$$$$$$  /$$$$$$$  /$$$$$$
| $$_____/                  | $$     /$$__  $$| $$__  $$|_  $$_/
| $$    /$$$$$$   /$$$$$$$ /$$$$$$  | $$  | $$| $$  | $$  | $$  
| $$$$$|____  $$ /$$_____/|_  $$_/  | $$$$$$$$| $$$$$$$/  | $$  
| $$__/ /$$$$$$$|  $$$$$$   | $$    | $$__  $$| $$____/   | $$  
| $$   /$$__  $$ |____  $$  | $$ /$$| $$  | $$| $$        | $$  
| $$  |  $$$$$$$ /$$$$$$$/  |  $$$$/| $$  | $$| $$       /$$$$$$
|__/   |_______/|_______/    |___/  |__/  |__/|__/      |______/

        """
    )

    
    yield


#初始化loguru日志
def register_logger() -> None:
    """
    系统日志

    :return:
    """
    setup_logging()
    set_customize_logfile()

def register_router(app: FastAPI) -> None:
    """
    注册路由
    """
    from APP.app.router import router
    app.include_router(router)

    ensure_unique_route_names(app)

def register_page(app: FastAPI):
    """
    分页查询

    :param app:
    :return:
    """
    add_pagination(app)